package net.magicalcloud.magicalcloud.view.viewImpl.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import net.magicalcloud.magicalcloud.R;
import net.magicalcloud.magicalcloud.entity.Files;
import net.magicalcloud.magicalcloud.transfer.MyDownloadManger;
import net.magicalcloud.magicalcloud.transfer.callback.OnDownload;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.BindView;
import butterknife.ButterKnife;

public class TransferActivity extends AppCompatActivity {

    @BindView(R.id.textView)
    TextView tv;
    @BindView(R.id.textView2)
    TextView tv2;

    public static int threadCount = 8;
    public static int runningThread=8;
    public int currentProgress=0;  //当前进度值..

    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer);
        ButterKnife.bind(this);


        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }

        //downLoad();

        Bundle b=null;
        if (getIntent() != null && getIntent().hasExtra(getPackageName()))
            b=getIntent().getBundleExtra(getPackageName());
        final Files f=(Files)b.getSerializable("data");

        tv.setText(f.getFileName()+"正在下载");
        MyDownloadManger.getInstance(this)
                .startDownload(f.getUrl(),
                        "/sdcard/MagicalCloud/",
                        f.getFileId(),
                        f.getFileName(),
                        new OnDownload() {
                            @Override
                            public void onDownloading(float speed, int finished) {
                                Message msg =Message.obtain(); //复用以前的消息..避免多次new...
                                msg.what = 4;
                                msg.obj="  已完成 "+finished+"%  已下载 "+speed+" M";
                                handler.sendMessage(msg);
                            }

                            @Override
                            public void onDownloadFinished(File downloadFile) {
                            }
                        });
//        MyDownloadManger.getInstance(this)
//                .startDownload("http://magicalcloud.peihuan.net/upload/1234655/3.rar",
//                        "/sdcard/MagicalCloud/",
//                        "1142",
//                        "3.rar",
//                        new OnDownload() {
//                            @Override
//                            public void onDownloading(float speed, int finished) {
//                                Message msg =Message.obtain(); //复用以前的消息..避免多次new...
//                                msg.what = 5;
//                                msg.obj="  已完成 "+finished+"%   已下载 "+speed+" M";
//                                handler.sendMessage(msg);
//                            }
//
//                            @Override
//                            public void onDownloadFinished(File downloadFile) {
//                            }
//                        });
    }

    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg){
            switch (msg.what) {
                case 1:
                    break;
                case 2:
                    break;
                case 3:

                case 4:
                    tv2.setText((String)msg.obj);
                    break;
                case 5:
                    tv.setText((String)msg.obj);
                default:
                    break;
            }
        }
    };

    public void downLoad(){

        final String path="http://magicalcloud.peihuan.net/upload/1234655/2.mp4";
        Runnable runnable=new Runnable(){
            //            String path = "http://192.168.199.172:8080/jdk.exe";

            public void run(){
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    int status = conn.getResponseCode();

                    if(status == 200){
                        int length = conn.getContentLength();       //单位为字节  ，1 kb=1024字节
                        System.out.println("文件总长度"+length);


                        File file = new File("/sdcard/MagicalCloud/");
                        if (!file.exists()) {
                            if(!file.mkdir())
                                System.out.println("文件夹创建失败");
                        }

                        RandomAccessFile raf = new RandomAccessFile("/sdcard/MagicalCloud/2.mp4","rwd");
                        raf.setLength(length);
                        raf.close();


                        //开启5个线程来下载当前资源..
                        int blockSize = length/threadCount ;

                        for(int threadID=1;threadID<=threadCount;threadID++){

                            int startIndex = (threadID-1)*blockSize;
                            int endIndex = threadID*blockSize -1;

                            if(threadID == threadCount){
                                endIndex = length;
                            }
                            System.out.println("线程"+threadID+"下载:---"+startIndex+"--->"+endIndex);
                            Runnable r=new DownLoadThread(threadID, startIndex, endIndex, path) ;
                            fixedThreadPool.execute(r);
                        }
                    }


                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            };

        };//9.09.48.991-9.10.04.318  60+12+4  20M / 76s
        //8    9.34.32- 9.35.47

        fixedThreadPool.execute(runnable);


    }


    public class DownLoadThread implements Runnable{

        private int ThreadID;
        private int startIndex;
        private int endIndex;
        private String path;

        public DownLoadThread(int ThreadID,int startIndex,int endIndex,String path){
            this.ThreadID = ThreadID;
            this.startIndex = startIndex;
            this.endIndex = endIndex;
            this.path = path;
        }
        @Override
        public void run() {
            // TODO Auto-generated method stub
            URL url;
            try {
                //检查是否存在还未下载完成的文件...
                File tempfile = new File("/sdcard/"+ThreadID+".txt");
                if(tempfile.exists() && tempfile.length()>0){
                    FileInputStream fis = new FileInputStream(tempfile);
                    byte temp[] =new byte[1024];
                    int leng = fis.read(temp);
                    int downlength = Integer.parseInt(new String(temp,0,leng));

                    int alreadydown = downlength -startIndex;

                    currentProgress += alreadydown;//发生断点之后记录下载的文件长度..

                    startIndex = downlength;
                    fis.close();
                }


                url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
                conn.setConnectTimeout(5000);

                //获取响应码..
                int status =conn.getResponseCode();

                if(status == 206){
                    InputStream in = conn.getInputStream();
                    RandomAccessFile raf =new RandomAccessFile("/sdcard/MagicalCloud/2.mp4", "rwd");

                    //文件开始写入..
                    raf.seek(startIndex);

                    int len =0;
                    byte[] buffer =new byte[1024];

                    //已经下载的数据长度..
                    int total = 0;


                    while((len = in.read(buffer))!=-1){
                        //记录当前数据下载的长度...
                        RandomAccessFile file = new RandomAccessFile("/sdcard/"+ThreadID+".txt", "rwd");
                        raf.write(buffer, 0, len);
                        total += len;
                        System.out.println("线程"+ThreadID+"total:"+total);
                        file.write((total+startIndex+"").getBytes());
                        file.close();

                        synchronized (TransferActivity.this) {
                            currentProgress += len; //获取当前总进度...
                            //progressBar progressDialog可以直接在子线程内部更新UI..由于源码内部进行了特殊的处理..
                            //pb.setProgress(currentProgress); //更改界面上的进度条进度..
                            Message msg =Message.obtain(); //复用以前的消息..避免多次new...
                            msg.what = 3;
                            msg.arg1=currentProgress;
                            handler.sendMessage(msg);

                        }
                    }

                    raf.close();
                    in.close();
                    System.out.println("线程："+ThreadID+"下载完毕");
                }else{
                    System.out.println("线程："+ThreadID+"下载失败");
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Message msg = new Message();
                msg.what = 1;
                msg.obj = e;
                handler.sendMessage(msg);
            }finally{
                synchronized (TransferActivity.this) {
                    runningThread--;

                    if(runningThread == 0){
                        for(int i=1;i<=threadCount;i++){
                            File file = new File("/sdcard/"+i+".txt");
                            file.delete();
                        }
                        Message msg =new Message();
                        msg.what = 2;
                        msg.obj ="下载完毕";
                        handler.sendMessage(msg);
                    }
                }

            }

        }

    }



}
